import {Form, Input, message, Select} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProcessFlowManageForm from './components/ProcessFlowManageForm';
import {allocateManager} from '@/services/process';
import {queryProcessFlow} from "@/services/product";
import {queryAccount} from "@/services/system";
import ProcessFlowForm from "@/pages/processing/processing-flow-manage/components/ProcessFlowForm";

const TableList = () => {
    const [createModalVisible, handleModalVisible] = useState(false);
    const [formTitle, setFormTitle] = useState('选择负责人');
    const [userData, setUserData] = useState([])
    const actionRef = useRef();
    const [formRef] = Form.useForm();
    const [row, setRow] = useState();
    const {Option} = Select;
    const handleUpdateModalVisible = (record) => {
      const admStaffIdsOld = record.admStaffIds ? record.admStaffIds.split(',').map(item => Number(item)) : []
      formRef.setFieldsValue({
        // ...record,
        admStaffIds: admStaffIdsOld
      })
      handleModalVisible(true)
      setRow(record)
    }

    const bundleAdmin = async (fields) => {
        const hide = message.loading('正在配置');
        fields.processId = row.processId
        try {
          await allocateManager({
            ...fields
          }).then(res => {
              if (res && res.status === '0') {
                hide();
                message.success('配置成功');
                if (actionRef.current) {
                  actionRef.current.reload();
                }
                handleModalVisible(false)
              } else {
                message.error(res.message);
              }
            }
          );
          return true;
        } catch
          (error) {
          hide();
          message.error('配置失败请重试！');
          return false;
        }
      }
    ;

    useEffect(() => {
      queryAccount({
        pageSize: 999999,
        pageNum: 1,
      }).then(res => {
        setUserData(res.result.records)
      })
    }, [])

    const onUserSearch = (v) => {
      queryAccount({
        pageSize: 999999,
        pageNum: 1,
        staffName: v
      }).then(res => {
        setUserData(res.result.records)
      })
    }
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        hideInForm: true,
        hideInSearch: true,
        render: (text, record, index, action) => {
          return `${index + 1}`
        }
      },
      // {
      //   title: '工艺段ID',
      //   dataIndex: 'processId',
      //   copyable: true,
      // },
      {
        title: '工艺段',
        dataIndex: 'processName',
        copyable: true,
        renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
          return <Input disabled={true}></Input>
        }
      },
      {
        title: '负责人',
        dataIndex: 'admStaffNames',
        hideInSearch: true,
        hideInForm: true
      },
      {
        title: '负责人',
        hideInTable: true,
        dataIndex: 'admStaffIds',
        hideInSearch: true,
        renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
          return <Select mode="multiple"
            //showSearch
                         defaultActiveFirstOption={false}
                         showArrow={true}
                         filterOption={false}
            //onSearch={(v) => onUserSearch(v)}
                         onChange={(v) => {
                           //console.log((v)
                         }}
                         notFoundContent={null}>
            {
              userData.map(item => {
                return <Option value={item.userId} key={item.userId}>{item.staffInfo.realName}</Option>
              })
            }
          </Select>
        }
      },
      // {
      //   title: '创建人',
      //   dataIndex: 'createBy',
      //   hideInSearch: true,
      //   hideInForm: true
      // },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        valueType: 'dateTime',
        hideInSearch: true,
        hideInForm: true
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => [
          <a onClick={() => handleUpdateModalVisible(record)}>
            选择负责人
          </a>
        ],
      },
    ];

    return (
      <PageContainer>
        <ProTable
          actionRef={actionRef}
          rowKey="processId"
          search={false}
          request={async (params, sorter, filter) => {
            // const param = {...params, pageNum: params.current, hidden: 0};
            const param = {pageSize: 999999, pageNum: 1, hidden: 0};
            const res = await queryProcessFlow(param)
            // const dataSource = res.result.records.map(item=>{
            //   item.admStaffIds = item.admStaffIds? item.admStaffIds.split(','): []
            //   // item.admStaffIds = item.admStaffNames? item.admStaffNames.split(','): []
            //   return item
            // })
            return {
              data: res.result.records,
              success: true,
              total: res.result.total
            }
          }}
          pagination={false}
          columns={columns}
        />

        {/*{*/}
        {/*  createModalVisible ? <ProcessFlowForm*/}
        {/*    data={row}*/}
        {/*    title={formTitle}*/}
        {/*    onCancel={() => handleModalVisible(false)}*/}
        {/*    modalVisible={createModalVisible}*/}
        {/*    onSubmit={(data) => {*/}
        {/*      bundleAdmin(data)*/}
        {/*    }}*/}
        {/*  /> : <></>*/}
        {/*}*/}
        <ProcessFlowForm
          data={row}
          title={formTitle}
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
          onSubmit={(data) => {
            bundleAdmin(data)
          }}
        />
      </PageContainer>
    );
  }
;

export default TableList;
